package com.copro.chemdb.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.copro.chemdb.beans.Account;
import com.copro.chemdb.utils.AccountUtils;
import com.copro.chemdb.utils.Constants;
import com.copro.simple.Application;

/**
 * 
 * Action to retrieve user and validate user with database
 * 
 * @author Peter
 * 
 */
public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Application app = Application.me(request);
		String name = request.getParameter("username");
		String password = request.getParameter("password");
		Account account = AccountUtils.getAccountByName(app, name);
		if (null != account && account.getPassword().equals(password)) {
			//save the user data
			request.getSession().setAttribute(Constants.USER, account);
			String url = (String) request.getSession().getAttribute(
					Constants.STOREDURL);
			if (null != url) {
				response.sendRedirect(url);
			} else {
				return new ActionForward("/", true);
			}
		} else {
			return new ActionForward("/login.jsp", true);
		}
		return null;
	}

}
